package com.demo.tran;

import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

@RocketMQTransactionListener(rocketMQTemplateBeanName = "rocketMQTemplate")
@Component
public class TransactionListener implements RocketMQLocalTransactionListener {

    // 模拟本地事务逻辑
    private boolean performBusinessLogic(String businessKey) {
        // 比如：插入订单、更新库存等
        System.out.println("执行本地事务，业务ID: " + businessKey);
        if(businessKey.equals("2")){
            return false;
        }
        return true;
    }

    // 模拟事务状态查询
    private boolean checkTransactionStatus(String businessKey) {
        // 查询数据库中该业务是否已成功
        System.out.println("回查事务状态，业务ID: " + businessKey);
        if(businessKey.equals("2")){
            return false;
        }
        return true;
    }

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        try {
            String businessKey = message.getHeaders().get("rocketmq_KEYS").toString();
            // 1. 执行本地数据库操作（如扣款、订单创建等）
            boolean result = performBusinessLogic(businessKey);

            // 2. 根据结果返回状态
            if (result) {
                return RocketMQLocalTransactionState.COMMIT;  // 提交消息
            } else {
                return RocketMQLocalTransactionState.ROLLBACK; // 回滚消息
            }
        } catch (Exception e) {
            // 异常情况下返回 UNKNOW，触发事务回查
            return RocketMQLocalTransactionState.UNKNOWN;
        }
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        // 根据消息内容查询本地事务状态（如查数据库记录）
        String businessKey = message.getHeaders().get("rocketmq_KEYS").toString();
        boolean isTransactionCommitted = checkTransactionStatus(businessKey);
        if (isTransactionCommitted) {
            return RocketMQLocalTransactionState.COMMIT;
        } else {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }
}